package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;

public class QdqssNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet=false;

		String[] regex={
			"http://www.qdqss.cn/[a-z]*/[a-z]*/[0-9]*/[0-9]*.shtml",
			"http://www.qdqss.cn/[a-z]*/[0-9]*/[0-9]*.shtml",
		};
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				bRet=true;
				break;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url=urlMeta.getUrl();
		String html=urlMeta.getHtml();
		if (html == null) {
		}
		String title="";
		String content="";
		String author = null;
		Long date= null;
		int commentNum=0;
		int clickNum=0;
		NewsMeta meta=new NewsMeta();
		meta.setUrl(url);
		meta.setType(0);
		Document doc=Jsoup.parse(html);
		urlMeta=null;
		/*
		 * 解析新闻标题
		 */
		title=doc.select("div.article_title h1").text();
		/*
		 * 解析时间
		 */
//		Pattern clickReg=Pattern.compile("www.qdqss.cn/c/shownews/zuozhe.ashx\\?id=[0-9]+&url=");
//		String matchDate=doc.select("script").toString();
//		Matcher matcher=clickReg.matcher(matchDate);
//		if(matcher.find()){
//			String group=matcher.group();
////			group += url;
//			UrlMeta dateMeta=CrawlHTML.responseToURL("http://"+group);
//			String string=dateMeta.getHtml();
//			date=DateUtils.matchDate(string);
//		}
		/*
		 * 解析内容
		 */
		date=DateUtils.matchDate(doc.select("div.article_title p").text());
		author=doc.select("div.article_title p").text();
		author = StringUtils.substringAfter(author, " ");
		content=HtmlCleaner.getContentHtml(url,doc.select("div.article_content"));
		meta.setTitle(title);
		meta.setContent(content);
		meta.setAuthor(author);
		meta.setDate(date);
		meta.setClickNum(clickNum);
		meta.setCommentNum(commentNum);

		return meta;
	}


	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	public static void main(String[] args) {
		String url="http://www.qdqss.cn/news/qingdao/20150918/14049.shtml";
		UrlMeta urlMeta=CrawlHTML.responseToURL(url);
		QdqssNewsAnalyse a=new QdqssNewsAnalyse();
		System.err.println(a.isDetailPage(url));
		NewsMeta parserHtml=a.parserHtml(urlMeta);
		System.out.println(parserHtml);


	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
